package com.lm.controller;

import com.lm.pojo.RegisterForm;
import com.lm.pojo.User;
import com.lm.pojo.UserInfo;
import com.lm.service.UserInfoService;
import com.lm.service.UserService;
import com.lm.util.RedisUtil;
import com.lm.util.YlbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private AuthenticationManager authenticationManager;

    @GetMapping({"/","/index"})
    public String index(Model model){
        model.addAttribute("class", "one");
        return "index";
    }


    @GetMapping("/toLogin")
    public String UserLogin(){
    return "login";
    }

    @GetMapping("/register")
    public String toRegister(){
        return "register";
    }


    @ModelAttribute("registerForm")
    public RegisterForm registerForm(){
        return new RegisterForm();
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public String register(@Validated RegisterForm registerForm, BindingResult result, Model model, HttpServletRequest request) {
        logger.info("开始注册，表单数据：{}", registerForm);
        try {
            // 判断校验是否有错
            if (result.hasErrors()) {
                // 输出校验错误信息
                List<FieldError> fieldErrors = result.getFieldErrors();
                for (FieldError fieldError : fieldErrors) {
                    logger.error("校验错误: 字段 {} - 错误信息 {}", fieldError.getField(), fieldError.getDefaultMessage());
                }
                return "register";
            }
            //判断密码是否一致
            if (!registerForm.getPassword().equals(registerForm.getRepassword())){
                model.addAttribute("pmsg", "密码不一致");
                return "register";
            }

            // 检查角色ID是否有效
            if (registerForm.getRoleId() != null && (registerForm.getRoleId() != 2 && registerForm.getRoleId() != 3)) {
                logger.error("无效的角色ID: {}", registerForm.getRoleId());
                model.addAttribute("msg", "无效的用户角色");
                return "register";
            }

            User user = new User();
            user.setUid(YlbUtils.getUuid());
            user.setRoleId(registerForm.getRoleId() != null ? registerForm.getRoleId() : 2); // 如果未选择角色，默认为普通用户
            user.setUsername(registerForm.getUsername());
            //密码加密
            String password = new BCryptPasswordEncoder().encode(registerForm.getPassword());
            user.setPassword(password);
            user.setAvatar("/images/avatar/man.png");
            user.setCreateTime(YlbUtils.getTime());
            user.setLoginTime(YlbUtils.getTime());

            try {
                //保存用户账号信息
                userService.saveUser(user);
                logger.info("用户账号信息保存成功，用户ID：{}", user.getUid());

                // 保存用户个人信息
                UserInfo userInfo = new UserInfo();
                userInfo.setUid(user.getUid());
                userInfo.setNickname("momo");
                userInfo.setEmail(registerForm.getEmail());
                userInfoService.SaveUserInfo(userInfo);

                model.addAttribute("msg","注册成功，快去登录吧~");
                return "register";
            } catch (DataIntegrityViolationException e) {
                logger.error("数据库完整性错误: {}", e.getMessage());
                if (e.getMessage().contains("role_id")) {
                    model.addAttribute("msg", "系统错误：无效的用户角色，请联系管理员");
                } else {
                    model.addAttribute("msg", "系统错误：数据保存失败，请稍后重试");
                }
                return "register";
            }
        } catch (Exception e) {
            logger.error("注册失败: {}", e.getMessage(), e);
            model.addAttribute("msg", "服务器错误，请稍后再试");
            return "register";
        }
    }

    @PostMapping("/findpwd")
    public String findPwd(@Validated RegisterForm registerForm, BindingResult result, Model model, HttpServletRequest request){
        try {
            //判断校验是否有错
            if (result.hasErrors()){
                return "findpwd";
            }
            
            //判断密码是否一致
            if (!registerForm.getPassword().equals(registerForm.getRepassword())){
                model.addAttribute("pmsg", "密码不一致");
                return "findpwd";
            }

            // 检查用户是否存在
            User user = userService.queryUserByName(registerForm.getUsername());
            if (user == null) {
                model.addAttribute("msg", "用户不存在");
                return "findpwd";
            }

            // 更新密码
            user.setPassword(new BCryptPasswordEncoder().encode(registerForm.getPassword()));
            userService.changePwd(user);
            
            model.addAttribute("msg", "密码修改成功，请重新登录");
            return "findpwd";
        } catch (Exception e) {
            logger.error("找回密码失败: {}", e.getMessage());
            model.addAttribute("msg", "服务器错误，请稍后再试");
            return "findpwd";
        }
    }

    /**
     * 判断是否是注册的邮箱
     */
    public Boolean isOkEmail(String username,String email){
        return userInfoService.isExistByUnameAndEmail(username, email);
    }

    /**
     * 判断用户名是否已使用
     */
    @GetMapping("/checkusername")
    @ResponseBody
    public String checkUsername(@RequestParam("username") String username){

        User user = userService.queryUserByName(username);
        if(user != null){
            return "用户名已使用";
        }
        return null;
    }

    @GetMapping("/findpwd")
    public String findPwd(){
        return "findpwd";
    }


}
